<script setup>
import { ref, toRefs, nextTick } from 'vue'
import { loadList } from '@/utils/util-table'
import QuerySearch from '@/components/plug-in/query-search'

const props = defineProps({
  url: {
    type: String,
    default: '',
    required: true
  },
  parseData: Function,
  columns: Array,
  rowKey: String,
  initial: {
    type: Boolean,
    default: true
  },
  queryDefault: {
    type: Object,
    default: () => {
      return {}
    }
  },
  querySettings: Array
})

const { url, parseData, columns, rowKey, initial, querySettings } = toRefs(props)

let query = ref(props.queryDefault)
let tableData = ref([])
let loading = ref(true)
let tableShow = ref(true)
let pagination = ref({
  hideOnSinglePage: true,
  responsive: true,
  pageSize: 15,
  total: 0,
  current: 1,
  showSizeChanger: true,
  pageSizeOptions: ['10', '15', '20', '30', '40', '50'],
  showTotal: (total) => `共 ${total} 条`
})

if(props.querySettings && props.querySettings.length){
  props.querySettings.forEach(item => {
    if ('default' in item && item.default !== false) {
      query.value[item.field] = item.default
    }
  })
}

/**
 * 展开收起
 * @param open
 */
let baseTableData = ref([])
let expandedRowKeys = ref([])
const expanded = (open = true) => {
  tableShow.value = false
  expandedRowKeys.value = []
  if (open) {
    baseTableData.value.forEach(item => {
      expandedRowKeys.value.push(item.NodeID)
    })
  }
  nextTick(() => {
    tableShow.value = true
  })
}

const reload = () => {
  loading.value = true
  let request_params = { ...query.value, Size: pagination.value.pageSize, Page: pagination.value.current }
  loadList(url.value, { params: request_params }).then(res => {
    loading.value = false
    baseTableData.value = res.list
    tableData.value = parseData.value ? parseData.value(res.list) : res.list
    pagination.value.total = res.count
  })
}

const searchQuery = (where) => {
  query.value = where
  reload()
}

const changeHandler = (page) => {
  pagination.value.current = page.current
  pagination.value.pageSize = page.pageSize
  reload()
}

if (initial.value) {
  reload()
}

defineExpose({
  expanded,
  reload
})
</script>

<template>
  <div class="table-pro">
    <div class="table-search" v-if="$slots.search || (querySettings && querySettings.length)">
      <query-search :settings="querySettings" @reload="searchQuery"/>
      <slot name="search"></slot>
    </div>
    <a-table
        v-if="tableShow"
        :loading="loading"
        bordered
        size="small"
        :rowKey="rowKey"
        :data-source="tableData"
        :columns="columns"
        :pagination="pagination"
        :scroll="{x: 'max-content'}"
        :default-expanded-row-keys="expandedRowKeys"
        @change="changeHandler"
    >
      <template #bodyCell="{ column, record }">
        <slot :column="column" :record="record"></slot>
      </template>
    </a-table>
  </div>
</template>
